package com.calms.study.config.dynamic_datasource;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author wangjunming
 * @since 2024-12-11 10:34
 */
@Slf4j
@Component
public class DynamicDatasourceConfig {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private ConfDatasourceMapper confDatasourceMapper;
    @Autowired
    private DefaultDataSourceCreator defaultDataSourceCreator;

    /**
     * 此处将通过主数据源查询数据库后转换为数据源添加到当前数据源中.
     */
    @PostConstruct
    public void initDataSourceByDb() {
        List<ConfDatasource> confDatasources = confDatasourceMapper
                .selectList(Wrappers.lambdaQuery(ConfDatasource.class)
                .eq(ConfDatasource::getDelFlag, "0"));
        for (ConfDatasource confDatasource : confDatasources) {
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            String url = confDatasource.getUrl();
            log.info("url:{}", url);
            Map<Object, Object> dataSourceUrlMap = MapUtil.builder()
                    .put("database_ip", confDatasource.getDatabaseIp())
                    .put("database_port", confDatasource.getDatabasePort())
                    .put("database_name", confDatasource.getDatabaseName()).build();
            String realJdbcUrl = StrUtil.format(url, dataSourceUrlMap);
            log.info("realJdbcUrl:{}", realJdbcUrl);
            dataSourceProperty.setUrl(realJdbcUrl);
            dataSourceProperty.setUsername(confDatasource.getUsername());
            dataSourceProperty.setPassword(confDatasource.getPassword());
            dataSourceProperty.setDriverClassName("com.mysql.cj.jdbc.Driver");
            DynamicRoutingDataSource routingDataSource = SpringUtil.getBean(DynamicRoutingDataSource.class);
            log.info("routingDataSource-->{}", routingDataSource);
            DataSource dataSource = defaultDataSourceCreator.createDataSource(dataSourceProperty);

            try {
                DriverManager.getConnection(realJdbcUrl, confDatasource.getUsername(), confDatasource.getPassword());
                routingDataSource.addDataSource(confDatasource.getDatasourceName(), dataSource);
            } catch (SQLException e) {
                log.warn("创建数据源失败, 数据源名称是->{}--错误信息如下.", confDatasource.getDatasourceName());
                log.error(e.getMessage());
            }
        }

        DynamicRoutingDataSource routingDataSourceBySpring = SpringUtil.getBean(DynamicRoutingDataSource.class);
        log.info("routingDataSourceBySpring-->{}", routingDataSourceBySpring);
        Map<String, DataSource> dataSources = routingDataSourceBySpring.getDataSources();
        log.info("dataSources-->{}", dataSources);

    }

}
